import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  List,
  ListItem,
  ListItemAvatar,
  ListItemText,
  Avatar,
  Button,
  TextField,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  IconButton,
  Badge,
  Tabs,
  Tab,
  Divider,
  Paper,
  Alert,
  CircularProgress
} from '@mui/material';
import {
  PersonAdd as PersonAddIcon,
  Message as MessageIcon,
  Search as SearchIcon,
  Close as CloseIcon
} from '@mui/icons-material';
import axios from 'axios';
import { useAuth } from '../contexts/AuthContext';

function FriendsModule() {
  const { user } = useAuth();
  const [friends, setFriends] = useState([]);
  const [requests, setRequests] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [searchDialogOpen, setSearchDialogOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState([]);
  const [searchLoading, setSearchLoading] = useState(false);
  const [chatDialogOpen, setChatDialogOpen] = useState(false);
  const [selectedFriend, setSelectedFriend] = useState(null);
  const [messages, setMessages] = useState([]);
  const [newMessage, setNewMessage] = useState('');
  const [activeTab, setActiveTab] = useState(0);

  // 获取好友列表
  const fetchFriends = async () => {
    try {
      setLoading(true);
      const response = await axios.get('/api/friends');
      setFriends(response.data);
    } catch (error) {
      console.error('获取好友列表失败:', error);
      setError('获取好友列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取好友请求
  const fetchRequests = async () => {
    try {
      const response = await axios.get('/api/friends/requests');
      setRequests(response.data);
    } catch (error) {
      console.error('获取好友请求失败:', error);
    }
  };

  // 初始加载
  useEffect(() => {
    if (user) {
      fetchFriends();
      fetchRequests();
    }
  }, [user]);

  // 搜索用户
  const handleSearch = async () => {
    if (!searchQuery.trim()) return;
    
    try {
      setSearchLoading(true);
      const response = await axios.get(`/api/users/search?q=${searchQuery}`);
      setSearchResults(response.data);
    } catch (error) {
      console.error('搜索用户失败:', error);
    } finally {
      setSearchLoading(false);
    }
  };

  // 发送好友请求
  const sendFriendRequest = async (userId) => {
    try {
      await axios.post(`/api/friends/request/${userId}`);
      // 更新搜索结果状态
      setSearchResults(prev => 
        prev.map(user => 
          user._id === userId 
            ? { ...user, requestSent: true } 
            : user
        )
      );
    } catch (error) {
      console.error('发送好友请求失败:', error);
    }
  };

  // 处理好友请求
  const handleRequest = async (requestId, action) => {
    try {
      await axios.patch(`/api/friends/request/${requestId}`, { action });
      // 刷新请求和好友列表
      fetchRequests();
      fetchFriends();
    } catch (error) {
      console.error('处理好友请求失败:', error);
    }
  };

  // 打开聊天对话框
  const openChat = async (friend) => {
    setSelectedFriend(friend);
    setChatDialogOpen(true);
    
    try {
      const response = await axios.get(`/api/messages/${friend._id}`);
      setMessages(response.data);
    } catch (error) {
      console.error('获取聊天记录失败:', error);
    }
  };

  // 发送消息
  const sendMessage = async () => {
    if (!newMessage.trim() || !selectedFriend) return;
    
    try {
      const response = await axios.post(`/api/messages/${selectedFriend._id}`, {
        content: newMessage
      });
      
      setMessages(prev => [...prev, response.data]);
      setNewMessage('');
    } catch (error) {
      console.error('发送消息失败:', error);
    }
  };

  return (
    <Box>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
        <Typography variant="h6">我的好友</Typography>
        <Button 
          startIcon={<PersonAddIcon />}
          onClick={() => setSearchDialogOpen(true)}
        >
          添加好友
        </Button>
      </Box>

      <Tabs 
        value={activeTab} 
        onChange={(e, newValue) => setActiveTab(newValue)}
        sx={{ mb: 2 }}
      >
        <Tab label="好友列表" />
        <Tab 
          label={
            <Badge badgeContent={requests.length} color="error">
              好友请求
            </Badge>
          } 
        />
      </Tabs>

      {activeTab === 0 ? (
        <Paper variant="outlined" sx={{ maxHeight: 300, overflow: 'auto' }}>
          {loading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
              <CircularProgress size={24} />
            </Box>
          ) : error ? (
            <Alert severity="error" sx={{ m: 2 }}>{error}</Alert>
          ) : friends.length > 0 ? (
            <List>
              {friends.map(friend => (
                <ListItem
                  key={friend._id}
                  secondaryAction={
                    <IconButton 
                      edge="end" 
                      onClick={() => openChat(friend)}
                    >
                      <MessageIcon />
                    </IconButton>
                  }
                >
                  <ListItemAvatar>
                    <Avatar src={friend.avatar}>
                      {friend.username.charAt(0).toUpperCase()}
                    </Avatar>
                  </ListItemAvatar>
                  <ListItemText 
                    primary={friend.username}
                    secondary={friend.bio || '这个用户很懒，什么都没留下'}
                  />
                </ListItem>
              ))}
            </List>
          ) : (
            <Box sx={{ p: 3, textAlign: 'center' }}>
              <Typography color="text.secondary">
                您还没有好友，点击"添加好友"开始社交吧！
              </Typography>
            </Box>
          )}
        </Paper>
      ) : (
        <Paper variant="outlined" sx={{ maxHeight: 300, overflow: 'auto' }}>
          {requests.length > 0 ? (
            <List>
              {requests.map(request => (
                <ListItem
                  key={request._id}
                  secondaryAction={
                    <Box>
                      <Button 
                        size="small" 
                        color="primary"
                        onClick={() => handleRequest(request._id, 'accept')}
                      >
                        接受
                      </Button>
                      <Button 
                        size="small" 
                        color="error"
                        onClick={() => handleRequest(request._id, 'reject')}
                      >
                        拒绝
                      </Button>
                    </Box>
                  }
                >
                  <ListItemAvatar>
                    <Avatar src={request.from.avatar}>
                      {request.from.username.charAt(0).toUpperCase()}
                    </Avatar>
                  </ListItemAvatar>
                  <ListItemText 
                    primary={request.from.username}
                    secondary={`请求时间: ${new Date(request.sentAt).toLocaleString()}`}
                  />
                </ListItem>
              ))}
            </List>
          ) : (
            <Box sx={{ p: 3, textAlign: 'center' }}>
              <Typography color="text.secondary">
                暂无好友请求
              </Typography>
            </Box>
          )}
        </Paper>
      )}

      {/* 搜索用户对话框 */}
      <Dialog 
        open={searchDialogOpen} 
        onClose={() => setSearchDialogOpen(false)}
        fullWidth
        maxWidth="sm"
      >
        <DialogTitle>
          搜索用户
          <IconButton
            onClick={() => setSearchDialogOpen(false)}
            sx={{ position: 'absolute', right: 8, top: 8 }}
          >
            <CloseIcon />
          </IconButton>
        </DialogTitle>
        <DialogContent>
          <Box sx={{ display: 'flex', mb: 2 }}>
            <TextField
              fullWidth
              placeholder="输入用户名搜索"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              variant="outlined"
              size="small"
            />
            <Button
              variant="contained"
              onClick={handleSearch}
              startIcon={<SearchIcon />}
              sx={{ ml: 1 }}
              disabled={searchLoading}
            >
              搜索
            </Button>
          </Box>

          {searchLoading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
              <CircularProgress size={24} />
            </Box>
          ) : searchResults.length > 0 ? (
            <List>
              {searchResults.map(user => (
                <ListItem
                  key={user._id}
                  secondaryAction={
                    user._id !== user._id && !user.isFriend && !user.requestSent ? (
                      <Button
                        variant="outlined"
                        size="small"
                        onClick={() => sendFriendRequest(user._id)}
                      >
                        添加
                      </Button>
                    ) : user.isFriend ? (
                      <Button
                        variant="outlined"
                        size="small"
                        disabled
                      >
                        已是好友
                      </Button>
                    ) : (
                      <Button
                        variant="outlined"
                        size="small"
                        disabled
                      >
                        已发送请求
                      </Button>
                    )
                  }
                >
                  <ListItemAvatar>
                    <Avatar src={user.avatar}>
                      {user.username.charAt(0).toUpperCase()}
                    </Avatar>
                  </ListItemAvatar>
                  <ListItemText 
                    primary={user.username}
                    secondary={user.bio || '这个用户很懒，什么都没留下'}
                  />
                </ListItem>
              ))}
            </List>
          ) : searchQuery ? (
            <Box sx={{ p: 3, textAlign: 'center' }}>
              <Typography color="text.secondary">
                未找到匹配的用户
              </Typography>
            </Box>
          ) : null}
        </DialogContent>
      </Dialog>

      {/* 聊天对话框 */}
      <Dialog
        open={chatDialogOpen}
        onClose={() => setChatDialogOpen(false)}
        fullWidth
        maxWidth="sm"
      >
        <DialogTitle>
          {selectedFriend?.username}
          <IconButton
            onClick={() => setChatDialogOpen(false)}
            sx={{ position: 'absolute', right: 8, top: 8 }}
          >
            <CloseIcon />
          </IconButton>
        </DialogTitle>
        <DialogContent>
          <Box 
            sx={{ 
              height: 300, 
              overflowY: 'auto',
              display: 'flex',
              flexDirection: 'column',
              p: 1
            }}
          >
            {messages.map((message, index) => (
              <Box
                key={message._id || index}
                sx={{
                  alignSelf: message.sender._id === user._id ? 'flex-end' : 'flex-start',
                  backgroundColor: message.sender._id === user._id ? 'primary.light' : 'grey.100',
                  color: message.sender._id === user._id ? 'white' : 'text.primary',
                  borderRadius: 2,
                  p: 1,
                  maxWidth: '70%',
                  mb: 1
                }}
              >
                <Typography variant="body2">{message.content}</Typography>
                <Typography variant="caption" sx={{ opacity: 0.7 }}>
                  {new Date(message.createdAt).toLocaleTimeString()}
                </Typography>
              </Box>
            ))}
          </Box>
        </DialogContent>
        <DialogActions sx={{ p: 2 }}>
          <TextField
            fullWidth
            placeholder="输入消息..."
            value={newMessage}
            onChange={(e) => setNewMessage(e.target.value)}
            variant="outlined"
            size="small"
            onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
          />
          <Button
            variant="contained"
            onClick={sendMessage}
            disabled={!newMessage.trim()}
          >
            发送
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}

export default FriendsModule; 